require 'config.rb'
require 'logger'
require 'cgi/session'
require 'fileutils'
require 'account/account.rb'
require 'extended.rb'


#
# === ToDo Dash ページ用のヘルパ
#
# Note:: 各ページに必要な処理を定義している．
#
# Author:: krdlab
#
class ToDoDashPageHelper

  LOGIN_ID = 'login_id'

  LOGIN_PW = 'login_password'

  LOGIN_PW2 = 'login_password2'

  LOG_FILE_DIRECTORY = 'log/todo_dash'

  LOG_FILE_PATH = LOG_FILE_DIRECTORY + '/todo_dash.log'

  def initialize
    @cgi = CGI.new
    @session = CGI::Session.new(@cgi)
    if(!File.exist?(LOG_FILE_DIRECTORY))
      FileUtils.makedirs(LOG_FILE_DIRECTORY)
    end
    @logger = Logger.new(LOG_FILE_PATH, 5)
    @logger.progname = "ToDo Dash"
  end

  def get_parameter(name)
    @cgi[name]
  end

private
  def set_session_value(name, value)
    @session[name] = value
    @session.update
  end

  def get_session_value(name)
    @session[name]
  end

  def log_debug(msg)
    @logger.debug("[#{Time.now}] #{msg}")
  end

public
  def redirect_to(path)
    ret = @cgi.header({'status' => "REDIRECT", 'Location' => path})
    log_debug("redirect header: #{ret}")
    return ret
  end

  def request_is_POST?
    return @cgi.request_method.upcase == "POST"
  end

  def try_login
    if not request_is_POST? then
      ticket = get_session_value('ticket')
      log_debug("ticket=#{ticket}")
      if !ticket.blank? then
        tmp_exists = !Account.find_by_ticket(ticket).nil?
        log_debug("exists ticket=#{tmp_exists}")
        return tmp_exists
      else
        return false
      end
    else
      # 明示的なログインの場合は一度 ticket を破棄
      set_session_value('ticket', nil)
      log_debug("delete ticket.")
      # login
      id = get_parameter(LOGIN_ID)
      pw = get_parameter(LOGIN_PW)
      log_debug("try login, id=#{id}, pw=#{pw}")

      ac = Account.login(id, pw)
      if not ac.nil? then
        set_session_value('ticket', ac.ticket)
        log_debug("login succeeded, id=#{ac.name}")
        return true
      else
        set_session_value('ticket', nil)
        log_debug("login failed")
        return false
      end
    end
  end

  def try_logout
    ac = get_account
    if not ac.nil? then
      ac.logout
      log_debug("logout succeeded, id=#{ac.name}")
    end
    return true
  end

  def check_put_passwords
    pw1 = get_parameter(LOGIN_PW)
    pw2 = get_parameter(LOGIN_PW2)
    if pw1.blank? or pw2.blank? then
      return false
    end
    return pw1 == pw2
  end

  def new_account
    # TODO 異常値対応
    id = get_parameter(LOGIN_ID)
    pw = get_parameter(LOGIN_PW)

    # すでに存在する名前は許可しない
    if Account.find_by_name(id) then
      log_debug("already exists, id=#{id}")
      return false
    end

    # 新しく作成
    ac = Account.new_account(id, pw)
    log_debug("new account succeeded, id=#{id}") if not ac.nil?
    return !ac.nil?
  end

  def get_account
    ticket = get_session_value('ticket')
    return Account.find_by_ticket(ticket)
  end

  def update_session
    @session.close
    @cgi.header
  end

  def delete_session
    @session.delete
    @cgi.header
  end
end

